package com.yugao.fintech.antelope.mps.core.sender;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.yugao.fintech.antelope.mps.api.constatnts.ChannelCodeEnum;
import com.yugao.fintech.antelope.mps.api.constatnts.ChannelTypeEnum;
import com.yugao.fintech.antelope.mps.api.constatnts.MsgPushStatus;
import com.yugao.fintech.antelope.mps.api.model.content.MsgContent;
import com.yugao.fintech.antelope.mps.core.PushTaskContext;
import com.yugao.fintech.antelope.mps.core.channel.ChannelClientManager;
import com.yugao.fintech.antelope.mps.core.channel.client.WxMaMsgClient;
import com.yugao.fintech.antelope.mps.core.parser.MaTemplateParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class WxMaSender implements MsgSender {
    @Autowired
    private ChannelClientManager channelClientManager;

    @Override
    public void sendMessage(PushTaskContext context) {
        context.setChannelCode(ChannelCodeEnum.WX_MINI_APP);
        log.info("send msg to wx_mini_app, msgPush: {}", context);
        MsgContent msgContent = (MsgContent) context.getMsgContent();
        List<WxMaSubscribeMessage.MsgData> data = new ArrayList<>();
        MaTemplateParser templateConfig = (MaTemplateParser) context.getTplConfig();
        templateConfig.getVarData().values().forEach(e -> data.add(new WxMaSubscribeMessage.MsgData(e.getKey(), String.valueOf(e.getValue()))));
        WxMaSubscribeMessage subscribeMessage = WxMaSubscribeMessage.builder()
                //这里添加的是推送消息的目标对象openId
                .toUser(msgContent.getToUser())
                //这里填写的就是在后台申请添加的模板ID
                .templateId(templateConfig.getTemplateId())
                //添加请求参数
                .data(data)
                //添加跳转链接，如果目标用户点击了推送的消息，则会跳转到小程序主页
                .page(msgContent.getPageUrl())
                .build();
        try {
            // 推送消息
            WxMaMsgClient wxMaMsgClient = (WxMaMsgClient) channelClientManager.getChannelClient(context.getChannelType());
            wxMaMsgClient.getWxMaService().getMsgService().sendSubscribeMsg(subscribeMessage);
            context.setChannelCode(wxMaMsgClient.channelCode());
        } catch (Exception e) {
            log.error("模板消息推送失败", e);
            context.setPushStatus(MsgPushStatus.FAIL);
            context.setPushResult(e.getMessage());
        }
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.WX_MINI_APP;
    }
}
